<!--
  * 登录
  *
  * @Author:    1024创新实验室-主任：卓大
  * @Date:      2022-09-12 22:34:00
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
  *
-->
<template>
  <div class="login-container">
    <div class="box-item desc" v-if="loginregister">
      <!-- <div class="welcome"> -->
      <div class="choNmin">
        <img class="picter" :src="choNmin" alt="" />
      </div>
      <div class="welcome">
        <p>欢迎登录 城桥中学报名系统</p>
        <div class="box1"></div>
      </div>

      <img class="welcome-img" :src="leftBg3" alt="" />
    </div>
    <div class="box-item login" v-if="loginregister">
      <!-- <img class="login-qr" :src="loginQR" /> -->
      <div>
        <div class="login-title">账号登录</div>
        <!-- <div class="box1"></div> -->
      </div>
      <a-form ref="formRef" class="login-form" :model="loginForm" :rules="rules">
        <a-form-item name="loginName">
          <a-input v-model:value.trim="loginForm.loginName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item name="emailCode" v-if="emailCodeShowFlag">
          <a-input-group compact>
            <a-input style="width: calc(100% - 110px)" v-model:value="loginForm.emailCode" autocomplete="on"
              placeholder="请输入邮箱验证码" />
            <a-button @click="sendSmsCode" class="code-btn" type="primary" :disabled="emailCodeButtonDisabled">
              {{ emailCodeTips }}
            </a-button>
          </a-input-group>
        </a-form-item>
        <a-form-item name="password">
          <a-input-password v-model:value="loginForm.password" autocomplete="on"
            :type="showPassword ? 'text' : 'password'" placeholder="请输入密码：至少三种字符，最小 8 位" />
        </a-form-item>
        <a-form-item name="captchaCode">
          <a-input class="captcha-input" v-model:value.trim="loginForm.captchaCode" placeholder="请输入验证码" />
          <img class="captcha-img" :src="captchaBase64Image" @click="getCaptcha" />
        </a-form-item>
        <!-- <a-form-item>
          <a-checkbox v-model:checked="rememberPwd">记住密码</a-checkbox>
        </a-form-item> -->
        <a-form-item>
          <div class="btn" @click="onLogin">登录</div>
        </a-form-item>
        <a-form-item style="text-align: center"> 没有账号? <a @click="goRegister">点此注册</a> </a-form-item>
      </a-form>
      <!-- <div class="more">
        <div class="title-box">
          <p class="line"></p>
          <p class="title">其他方式登录</p>
          <p class="line"></p>
        </div>
        <div class="login-type">
          <img :src="wechatIcon" />
          <img :src="aliIcon" />
          <img :src="douyinIcon" />
          <img :src="qqIcon" />
          <img :src="weiboIcon" />
          <img :src="feishuIcon" />
          <img :src="googleIcon" />
        </div>
      </div> -->
    </div>
    <div class="box-item box-item2 login" v-else>
      <div class="login-title">
        <span>账号注册</span>
        <div style="margin: 10px;"><span style="font-size: 16px;color: red;">报名提醒： 请使用学生个人信息认真填写</span></div>
      </div>
      <a-form ref="formRef2" class="login-form" :model="loginForm2" :rules="rules2" :label-col="{span: 5}" >
        <a-row :gutter="24" justify="space-around" align="middle">
          <a-col :span="12">
            <a-form-item name="actualName" label="姓 名">
              <a-input v-model:value.trim="loginForm2.actualName" placeholder="请输入姓名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="card" label="身份证">
              <a-input v-model:value.trim="loginForm2.card" placeholder="请输入身份证号码" @change="cardChange" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="loginName" label="账 号">
              <a-input v-model:value.trim="loginForm2.loginName" placeholder="请输入登录账号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="gender" label="性 别">
              <a-radio-group v-model:value="loginForm2.gender">
                <a-radio value="1">男</a-radio>
                <a-radio value="2">女</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="loginPwd" label="密 码 ">
              <a-input-password v-model:value="loginForm2.loginPwd" autocomplete="on"
                :type="showPassword ? 'text' : 'password'" placeholder="请输入密码：至少三种字符，最小 8 位" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="checkPass" label="确认密码">
              <a-input-password v-model:value="loginForm2.checkPass" autocomplete="on"
                :type="showPassword2 ? 'text' : 'password'" placeholder="请再次输入确认密码" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="phone" label="手机号">
              <a-input v-model:value.trim="loginForm2.phone" placeholder="请输入手机号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="邮 箱">
              <a-input v-model:value.trim="loginForm2.mail" placeholder="请输入邮箱" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item name="captchaCode" label="验证码">
              <a-input class="captcha-input" v-model:value.trim="loginForm2.captchaCode" placeholder="请输入验证码" />
              <img class="captcha-img" :src="captchaBase64Image" @click="getCaptcha" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item>
          <div class="btn" @click="onRegister">注册</div>
        </a-form-item>
        <a-form-item> 已有账号? <a @click="goLogin">点此登录</a> </a-form-item>
      </a-form>
    </div>
  </div>
  <!-- footer 版权公司信息 -->
  <a-layout-footer class="layout-footer">
        <smart-footer />
      </a-layout-footer>
</template>
<script setup>
import { message } from 'ant-design-vue';
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { loginApi } from '/@/api/system/login-api';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { LOGIN_DEVICE_ENUM } from '/@/constants/system/login-device-const';
import { useUserStore } from '/@/store/modules/system/user';
import loginQR from '/@/assets/images/login/login-qr.png';
import leftBg2 from '/@/assets/images/login/left-bg2.png';
import leftBg3 from '/@/assets/images/login/left-bg3.png';
import choNmin from '/@/assets/images/login/chonmin.png';
import wechatIcon from '/@/assets/images/login/wechat-icon.png';
import aliIcon from '/@/assets/images/login/ali-icon.png';
import douyinIcon from '/@/assets/images/login/douyin-icon.png';
import qqIcon from '/@/assets/images/login/qq-icon.png';
import weiboIcon from '/@/assets/images/login/weibo-icon.png';
import feishuIcon from '/@/assets/images/login/feishu-icon.png';
import googleIcon from '/@/assets/images/login/google-icon.png';
import SmartFooter from '/@/layout/components/smart-footer/index.vue';

import { buildRoutes } from '/@/router/index';
import { smartSentry } from '/@/lib/smart-sentry';
import { encryptData } from '/@/lib/encrypt';
import { localSave } from '/@/utils/local-util.js';
import LocalStorageKeyConst from '/@/constants/local-storage-key-const.js';

//--------------------- 登录表单 ---------------------------------

const loginForm = reactive({
  loginName: '',
  password: '',
  captchaCode: '',
  captchaUuid: '',
  loginDevice: LOGIN_DEVICE_ENUM.PC.value,
});
const loginForm2 = reactive({
  actualName: '',
  loginName: '',
  gender: '',
  loginPwd: '',
  checkPass: '',
  card: '',
  phone: '',
  mail: '',
  captchaCode: '',
  loginDevice: LOGIN_DEVICE_ENUM.PC.value,
  captchaUuid: '',
  disabledFlag: 0,
  deletedFlag: 0,
  administratorFlag: 0,
});
const rules = {
  loginName: [{ required: true, message: '用户名不能为空' }],
  password: [{ required: true, message: '密码不能为空' }],
  captchaCode: [{ required: true, message: '验证码不能为空' }],
};
const validatePass = async (_rule, value) => {
  if (value === '') {
    return Promise.reject('请输入密码');
  } else {
    if (loginForm2.checkPass !== '') {
      formRef2.value.validateFields('checkPass');
    }
    return Promise.resolve();
  }
};

const validatePass2 = async (_rule, value) => {
  console.log(value);
  if (value === '') {
    return Promise.reject('请重新输入密码');
  } else if (value !== loginForm2.loginPwd) {
    return Promise.reject('两个输入不一致！');
  } else {
    return Promise.resolve();
  }
};
const rules2 = {
  actualName: [
    { required: true, message: '姓名不能为空' },
    { pattern: /^[\u4e00-\u9fa5]{2,6}$/, message: '请输入正确的姓名' },
  ],
  loginName: [{ required: true, message: '登录账号不能为空' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  loginPwd: [{ required: true, trigger: 'change' },
  { pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,}$/, message: '密码必须包含字母特殊符号加数字3种组合' }],
  checkPass: [{ required: true, validator: validatePass2, trigger: 'change' }],
  card: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号码' },
  ],
  phone: [
    { required: true, message: '请输入用户手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' },
  ],
  mail: [
    { required: true, type: 'email', message: '请输入邮箱地址', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '请输入正确的邮箱地址' },
  ],
  captchaCode: [{ required: true, message: '验证码不能为空' }],
};

const showPassword = ref(false);
const showPassword2 = ref(false);
const router = useRouter();
const formRef = ref();
const formRef2 = ref();
const rememberPwd = ref(false);
const loginregister = ref(true);

onMounted(() => {
  document.onkeyup = (e) => {
    if (e.keyCode === 13) {
      onLogin();
    }
  };
});

onUnmounted(() => {
  document.onkeyup = null;
});
// 根据身份证获取性别
function cardChange() {
  let str = loginForm2.card.toString();
  if (str.length == 18) {
    let sex = str[str.length - 2];
    if (sex % 2 == 1) {
      loginForm2.gender = '1';
    } else {
      loginForm2.gender = '2';
    }
  }
}
async function goRegister() {
  loginregister.value = !loginregister.value;
  getCaptcha();
}
async function goLogin() {
  loginregister.value = !loginregister.value;
  getCaptcha();
}

//注册
async function onRegister() {
  formRef2.value.validate().then(async () => {
    try {
      SmartLoading.show();
      // 密码加密
      let encryptPasswordForm = Object.assign({}, loginForm2, {
        loginPwd: encryptData(loginForm2.loginPwd),
        card: encryptData(loginForm2.card),
        checkPass: '',
      });
      console.log(encryptPasswordForm);
      const res = await loginApi.register(encryptPasswordForm);
      console.log(res);
      if (res.code == 0) {
        message.success('注册成功');
        loginregister.value = !loginregister.value;
      }
    } catch (e) {
      if (e.data && e.data.code !== 0) {
        loginForm2.captchaCode = '';
        getCaptcha();
      }
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  });
}
//登录
async function onLogin() {
  formRef.value.validate().then(async () => {
    try {
      SmartLoading.show();
      // 密码加密
      let encryptPasswordForm = Object.assign({}, loginForm, {
        password: encryptData(loginForm.password),
      });
      const res = await loginApi.login(encryptPasswordForm);
      stopRefreshCaptchaInterval();
      localSave(LocalStorageKeyConst.USER_TOKEN, res.data.token ? res.data.token : '');
      message.success('登录成功');
      //更新用户信息到pinia
      useUserStore().setUserLoginInfo(res.data);
      //构建系统的路由
      buildRoutes();
      router.push('/home');
    } catch (e) {
      if (e.data && e.data.code !== 0) {
        loginForm.captchaCode = '';
        getCaptcha();
      }
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  });
}

//--------------------- 验证码 ---------------------------------

const captchaBase64Image = ref('');
async function getCaptcha() {
  try {
    let captchaResult = await loginApi.getCaptcha();
    captchaBase64Image.value = captchaResult.data.captchaBase64Image;
    loginForm.captchaUuid = captchaResult.data.captchaUuid;
    loginForm2.captchaUuid = captchaResult.data.captchaUuid;
    beginRefreshCaptchaInterval(captchaResult.data.expireSeconds);
  } catch (e) {
    console.log(e);
  }
}

let refreshCaptchaInterval = null;
function beginRefreshCaptchaInterval(expireSeconds) {
  if (refreshCaptchaInterval === null) {
    refreshCaptchaInterval = setInterval(getCaptcha, (expireSeconds - 5) * 1000);
  }
}

function stopRefreshCaptchaInterval() {
  if (refreshCaptchaInterval != null) {
    clearInterval(refreshCaptchaInterval);
    refreshCaptchaInterval = null;
  }
}

onMounted(() => {
  getCaptcha();
  getTwoFactorLoginFlag();
});

//--------------------- 邮箱验证码 ---------------------------------

const emailCodeShowFlag = ref(false);
let emailCodeTips = ref('获取邮箱验证码');
let emailCodeButtonDisabled = ref(false);
// 定时器
let countDownTimer = null;
// 开始倒计时
function runCountDown() {
  emailCodeButtonDisabled.value = true;
  let countDown = 60;
  emailCodeTips.value = `${countDown}秒后重新获取`;
  countDownTimer = setInterval(() => {
    if (countDown > 1) {
      countDown--;
      emailCodeTips.value = `${countDown}秒后重新获取`;
    } else {
      clearInterval(countDownTimer);
      emailCodeButtonDisabled.value = false;
      emailCodeTips.value = '获取验证码';
    }
  }, 1000);
}

// 获取双因子登录标识
async function getTwoFactorLoginFlag() {
  try {
    let result = await loginApi.getTwoFactorLoginFlag();
    emailCodeShowFlag.value = result.data;
  } catch (e) {
    smartSentry.captureError(e);
  }
}

// 发送邮箱验证码
async function sendSmsCode() {
  try {
    SmartLoading.show();
    let result = await loginApi.sendLoginEmailCode(loginForm.loginName);
    message.success('验证码发送成功!请登录邮箱查看验证码~');
    runCountDown();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}
</script>
<style lang="less" scoped>
@import './login.less';
.layout-footer {
  position: fixed;
  width: 100%;
  text-align: center;
  bottom:10px;
    padding: 7px 0px;
    display: flex;
    justify-content: center;
  }
</style>
